﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Ace;
using Ace.Application.Common;
using Ace.Application.Wiki;
using Ace.Entity.Wiki;
using Ace.IdStrategy;
using Ace.Web.Mvc;
using Ace.Web.Mvc.Authorization;
using Ace.Web.Mvc.Models;
using Chloe.Admin.Common;
using Chloe.Admin.Common.Tree;
using Microsoft.AspNetCore.Mvc;

using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Exceptions;
using Ace.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Senparc.Weixin;
using Senparc.CO2NET.Extensions;
using Senparc.Weixin.TenPay;
using Senparc.Weixin.TenPay.V3;
using NLog;
using Senparc.CO2NET.Utilities;
using Chloe.Admin.Models;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using System.Security.Cryptography;
using System.Text;
using System.Net.Http;
using System.Security.Authentication;
using System.Net.Http.Headers;
using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp;
using Ace.Web.Helpers;
using System.Collections.Specialized;
using System.Web;
using System.Net;

namespace Chloe.Admin.Controllers
{
    public class APIController : WebController
    { 
        public IActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 获取OpenID
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <param name="jscode"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult JsCode2Json(string jscode)
        {
            //JsonResultData jd = new JsonResultData();
            string appid = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
            string secret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();
            string IsDebug = Globals.Configuration["AppSettings:IsDebug"].ToString();
            JsCode2JsonResult data = Senparc.Weixin.WxOpen.AdvancedAPIs.Sns.SnsApi.JsCode2Json(appid, secret, jscode);
            data.P2PData = IsDebug;
            return this.SuccessData(data);
        }


        public ActionResult GetPhoneNumber(string jscode, string encryptedData, string IV)
        {
            string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
            string WxOpenAppSecret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();

            if (!string.IsNullOrEmpty(jscode) && !string.IsNullOrEmpty(encryptedData) && !string.IsNullOrEmpty(IV))
            {
                string _posdata = "appid=" + WxOpenAppId + "&secret=" + WxOpenAppSecret + "&js_code=" + jscode + "&grant_type=authorization_code";
                string _url = "https://api.weixin.qq.com/sns/jscode2session";//获取openid
                string _data = HttpPost(_url, _posdata);
                if (_data.Contains("\"openid\""))
                {
                    dynamic _modal = Newtonsoft.Json.Linq.JToken.Parse(_data) as dynamic;
                    string _openid = _modal.openid;
                    string _session_key = _modal.session_key;

                    byte[] encryData = Convert.FromBase64String(encryptedData);  // strToToHexByte(text);
                    RijndaelManaged rijndaelCipher = new RijndaelManaged();
                    rijndaelCipher.Key = Convert.FromBase64String(_session_key); // Encoding.UTF8.GetBytes(AesKey);
                    rijndaelCipher.IV = Convert.FromBase64String(IV);// Encoding.UTF8.GetBytes(AesIV);
                    rijndaelCipher.Mode = CipherMode.CBC;
                    rijndaelCipher.Padding = PaddingMode.PKCS7;
                    ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                    byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                    string result = Encoding.Default.GetString(plainText);
                    //动态解析result 成对象
                    dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                    //return model.phoneNumber;
                    //mobile = model.phoneNumber;
                    var obj = new { mobile = model.phoneNumber, openid = _openid };
                    return this.SuccessData(obj);
                }
                else
                {
                    return this.FailedMsg("请重试");
                }
            }
            else
            {
                return this.FailedMsg("请求错误，请重试");
            }
        }

        public string HttpPost(string uri, string jsontxt)
        {
            var handler = new HttpClientHandler();

            //X509Certificate2 certificate = GetMyX509Certificate(certName);

            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.SslProtocols = SslProtocols.Tls12;
            //handler.ClientCertificates.Add(certificate);
            var retData = string.Empty;
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
                var content = new StringContent(jsontxt);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
                var response = httpClient.PostAsync(uri, content).Result;
                retData = response.Content.ReadAsStringAsync().Result;
            }
            return retData;
        }


        public string HttpGet(string Url)
        {
            string retData = string.Empty;
            //创建HttpClient（注意传入HttpClientHandler）
            var handler = new HttpClientHandler() { AutomaticDecompression = System.Net.DecompressionMethods.None };//.GZip };

            using (var http = new HttpClient(handler))
            {
                var response = http.GetAsync(Url).Result;
                if (response.IsSuccessStatusCode)
                {
                    retData = response.Content.ReadAsStringAsync().Result;
                }  
            }
            return retData;
        }


        public ActionResult WeChatLogin(string OpenID, string Mobile, string UserName, string UserIcon = "", string FromID = "", int ShopID = 1)
        {
            if (!string.IsNullOrEmpty(OpenID))
            {
                Users modle = this.CreateService<IUsersService>().GetModelByMobile(Mobile);
                Shop shop = this.CreateService<IShopService>().GetModel(ShopID);
                if (modle != null)
                {
                    UpdateUsersInput input = new UpdateUsersInput();
                    input.CreateDate = modle.CreateDate;                    
                    input.FromID = modle.FromID;
                    input.Id = modle.Id;                    
                    input.Mobile = modle.Mobile;
                    input.OpenID = OpenID;
                    input.RoleID = modle.RoleID;                    
                    input.ShopID = modle.ShopID;
                    input.ST = modle.ST;
                    input.UserIcon = modle.UserIcon;
                    input.UserName = modle.UserName;

                    input.TrueName = modle.TrueName;
                    input.ProvinceID = modle.ProvinceID;
                    input.CityID = modle.CityID;
                    input.PartID = modle.PartID;
                    input.CompanyName = modle.CompanyName;
                    input.Service = modle.Service;
                    input.Job = modle.Job;
                    input.Tel = modle.Tel;
                    input.Code = modle.Code;
                    input.Address = modle.Address;



                    this.CreateService<IUsersService>().Update(input);


                    return this.SuccessData(modle);
                }
                else
                {
                    AddUsersInput addUsersInput = new AddUsersInput();
                    addUsersInput.CreateDate = DateTime.Now; 
                    addUsersInput.FromID = FromID; 
                    addUsersInput.Mobile = Mobile;
                    addUsersInput.RoleID = 0; 
                    addUsersInput.ST = 1;//无须审核
                    addUsersInput.UserName = UserName;                    
                    addUsersInput.OpenID = OpenID;
                    addUsersInput.UserIcon = UserIcon;
                    addUsersInput.ShopID = ShopID;


                    addUsersInput.TrueName = "";
                    addUsersInput.ProvinceID = 0;
                    addUsersInput.CityID = 0;
                    addUsersInput.PartID = 0;
                    addUsersInput.CompanyName = "";
                    addUsersInput.Service = "";
                    addUsersInput.Job = "";
                    addUsersInput.Tel = "";
                    addUsersInput.Code = "";
                    addUsersInput.Address = "";

                    Users users = this.CreateService<IUsersService>().Add(addUsersInput);

                     

                    return this.SuccessData(users);
                }



            }
            else
            {
                return this.FailedMsg("");
            }

        }

        public ActionResult UserLogin(string Mobile)
        {
            Users info = this.CreateService<IUsersService>().GetModelByMobile(Mobile);
            if(info!=null)
            {
                return this.SuccessData(info);
            }
            else
            {
                return this.FailedMsg("手机号不存在");
            }
        }

        public ActionResult UpdateUserIcon(string OpenID, string Mobile, string UserIcon, string UserName)
        {
            this.CreateService<IUsersService>().UpdateUserInfo(OpenID, Mobile, UserIcon, UserName);
            return this.SuccessMsg();
        }

        public ActionResult QRCode(string uid, int ShopID = 1)
        {
            string url = "/QRCode/" + uid + "_" + ShopID + ".jpg";
            string file_path = Globals.AppRootPath + "\\wwwroot\\QRCode\\";
            if (!Directory.Exists(file_path))
            {
                Directory.CreateDirectory(file_path);
            }
            file_path += uid + "_" + ShopID + ".jpg";
            if (!System.IO.File.Exists(file_path))
            {
                string appid = Globals.Configuration["AppSettings:WxOpenAppId"];
                string wxUrl = "pages/start/index?uid=" + uid + "&id=" + ShopID;
                WxAppApi.GetWxaCode(appid, file_path, wxUrl);
            }

            return  this.SuccessData(Globals.Configuration["AppSettings:FileDomain"] + url);
        }

        /// <summary>
        /// 商家列表 距离计算
        /// </summary>
        /// <param name="GPS_X"></param>
        /// <param name="GPS_Y"></param>
        /// <returns></returns>
        public ActionResult ShopList(int ProvinceID,int BrandID,string Key="")
        {
            List<ShopSample> list = this.CreateService<IShopService>().GetShopList(ProvinceID, BrandID, Key);
            return this.SuccessData(list);
        }

        public ActionResult GetShopPageList(Pagination pagination, int ProvinceID, int BrandID, string Key = "")
        {
            PagedData<ShopSample> pagedData = this.CreateService<IShopService>().GetShopPageList(pagination, ProvinceID, BrandID, Key);
            return this.SuccessData(pagedData);
        }


        public ActionResult ShopInfo(int ShopID)
        {
            Shop shop = this.CreateService<IShopService>().GetModel(ShopID);
            return this.SuccessData(shop);
        }


        public ActionResult LinkList(int ShopID, int SortID, string keyword)
        {
            List<Link> list = this.CreateService<ILinkService>().GetShopLinkList(ShopID,SortID, keyword);
            return this.SuccessData(list);
        }


        public ActionResult ProSortList(string Pid="", string keyword="")
        {
            List<Pro_Sort> list = this.CreateService<IPro_SortService>().GetList(Pid, keyword);
            return this.SuccessData(list);
        }

        public ActionResult ProTopList(int Num=4,int IsTop=0,int ShopID=0)
        {
            List<Product> list = this.CreateService<IProductService>().GetTopList(Num, IsTop, ShopID);
            return this.SuccessData(list);
        }

        public ActionResult ProHotList(int Num = 4, int IsHot = 0,int ShopID=0)
        {
            List<Product> list = this.CreateService<IProductService>().GetHotList(Num, IsHot, ShopID);
            return this.SuccessData(list);
        }

        public ActionResult BrandList(int ShopID, int IsTop = 0, string keyword = "")
        {
            List<Brand> list = this.CreateService<IBrandService>().GetShopBrandList(ShopID,IsTop, keyword);
            return this.SuccessData(list);
        }

        public ActionResult BrandPageList(Pagination pagination, int IsTop = 0, string keyword = "")
        {
            PagedData<Brand> pagedData = this.CreateService<IBrandService>().GetPageData(pagination, IsTop,keyword);
            return this.SuccessData(pagedData);
        }

        public ActionResult BrandDetail(string id)
        {
            Brand info = this.CreateService<IBrandService>().GetModel(id);
            return this.SuccessData(info);
        }

        public ActionResult BrandProduct(string id)
        {
            List<Product> list = this.CreateService<IProductService>().GetProductListByBrandID(id);
            return this.SuccessData(list);
        }

        public ActionResult NewsList(int ShopID, int Num=4, int SortID=0,int IsValid=1)
        {
            List<News> list = this.CreateService<INewsService>().GetShopNewsList(Num,SortID, ShopID, IsValid).ToList();
            return this.SuccessData(list);
        }

        public ActionResult NewsPageList(Pagination pagination, int SortID, int IsValid=-1, string keyword="")
        {
            PagedData<News> pagedData = this.CreateService<INewsService>().GetPageData(pagination, SortID, IsValid, keyword);
            return this.SuccessData(pagedData);
        }
         


        public ActionResult NewsDetail(string id)
        {
            News news = this.CreateService<INewsService>().GetModel(id);
            return this.SuccessData(news);
        }

        public ActionResult CommentList(string Fid,int Num=10)
        {
            List<Comment> list = this.CreateService<ICommentService>().GetList(Fid, Num).ToList();
            return this.SuccessData(list);
        }

        [HttpPost]
        public ActionResult CommentPost(AddCommentInput addCommentInput)
        {
            addCommentInput.CreateDate = DateTime.Now;            
            this.CreateService<ICommentService>().Add(addCommentInput);
            return this.SuccessMsg();
        }

        public ActionResult CateList(string Pid)
        {
            List<Pro_Sort> pro_Sorts = this.CreateService<IPro_SortService>().GetList(Pid, "");
            return this.SuccessData(pro_Sorts);
        }

        public ActionResult CateInfo(string id)
        {
            ProSortInfo curCateInfo = new ProSortInfo();            
            Pro_Sort pro_Sort = this.CreateService<IPro_SortService>().GetModle(id);

            curCateInfo.Icon = pro_Sort.Icon;
            curCateInfo.Id = pro_Sort.Id;
            curCateInfo.Pid = pro_Sort.Pid;
            curCateInfo.ProCount = pro_Sort.ProCount;
            curCateInfo.SortCode = pro_Sort.SortCode;
            curCateInfo.SubSortList = this.CreateService<IPro_SortService>().GetList(id, "");
            curCateInfo.Title = pro_Sort.Title;
            curCateInfo.ImageUrl = pro_Sort.ImageUrl;
            curCateInfo.Summary = pro_Sort.Summary;


            return this.SuccessData(curCateInfo);
        }

        public ActionResult ProductCount(string SortID="")
        {
            int count = this.CreateService<IProductService>().GetProductCount(SortID);
            return this.SuccessData(count);
        }

        public ActionResult ProductList(int ShopID, int Num, string SortID)
        {
            List<Product> list = this.CreateService<IProductService>().GetShopProductList(ShopID,Num, SortID);
            return this.SuccessData(list);
        }

        /// <summary>
        /// 置顶推荐
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="ProSortID"></param>
        /// <param name="keyword"></param>
        /// <param name="OrderType"></param>
        /// <returns></returns>
        public ActionResult ProductTopList(Pagination pagination, string ProSortID, string keyword, int OrderType = 0)
        {
            PagedData<Product> pagedData = this.CreateService<IProductService>().GetTopPageData(pagination, 1, ProSortID, keyword, OrderType);
            return this.SuccessData(pagedData);
        }

        /// <summary>
        /// 人气推荐
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="ProSortID"></param>
        /// <param name="keyword"></param>
        /// <param name="OrderType"></param>
        /// <returns></returns>
        public ActionResult ProductHotList(Pagination pagination, string ProSortID, string keyword, int OrderType = 0)
        {
            PagedData<Product> pagedData = this.CreateService<IProductService>().GetHotPageData(pagination, 1, ProSortID, keyword, OrderType);
            return this.SuccessData(pagedData);
        }

        public ActionResult ProductPageList(Pagination pagination,int ShopID, string ProSortID, string keyword, int OrderType = 0)
        {
            PagedData<Product> pagedData = this.CreateService<IProductService>().GetShopProductPageList(pagination,ShopID, ProSortID, keyword, OrderType);
            return this.SuccessData(pagedData);
        }


        public ActionResult ProductPageList2(Pagination pagination,string SortID, string keyword)
        {
            PagedData<Product> pagedData = this.CreateService<IProductService>().GetPageData2(pagination, SortID, keyword);
            return this.SuccessData(pagedData);
        }

        

        public ActionResult ProductInfo(string id,int hit=0,string userid="")
        {
            IProductService productService = this.CreateService<IProductService>();
            Product product = productService.GetModle(id);

            //更新点击量
            if(hit==1)
            {
                productService.UpDateHit(id,product.Hit+1);
            }

            //访问记录
            if(!string.IsNullOrEmpty(userid))
            {
                IProduct_rcdService rcdService = this.CreateService<IProduct_rcdService>();
                Product_rcd rcd = this.CreateService<IProduct_rcdService>().GetModel(userid, id);
                if(rcd!=null)
                {
                    rcdService.UpdateHit(rcd.Id, rcd.Hit + 1);
                }
                else
                {
                    AddProduct_rcdInput input = new AddProduct_rcdInput();
                    input.CreateDate = DateTime.Now;
                    input.Hit = 1;
                    input.ProductID = id;
                    input.UpdateTime = DateTime.Now;
                    input.UserID = userid;
                    rcdService.Add(input);
                }

            }

            ProductInfo modle = new ProductInfo();
            modle.product = product;

            AdminSession adminSession = this.CurrentSession;
            if(adminSession!=null)
            {
                string UserID = adminSession.UserId;
                int Count = this.CreateService<IPro_CollectionService>().Count(UserID, id);
                if(Count>0)
                {
                    modle.HasCollect = 1;
                }
                else
                {
                    modle.HasCollect = 0;
                }
            }
            else
            {
                modle.HasCollect = 0;
            }

            List<Product_Size> sizelist = this.CreateService<IProduct_SizeService>().GetList(product.ProductCode);
            modle.SizeList = sizelist;


            if(product.BrandID.IsNotNullOrEmpty())
            {
                Brand brand = this.CreateService<IBrandService>().GetModel(product.BrandID);
                modle.brand = brand;
            }
            else
            {
                modle.brand = null;
            }

            return this.SuccessData(modle);
        }

        public ActionResult Pro_CollectionAdd(string ProductID,string UserID)
        {
            AddPro_CollectionInput addPro_CollectionInput = new AddPro_CollectionInput();
            addPro_CollectionInput.CreateDate = DateTime.Now;
            addPro_CollectionInput.ProductID = ProductID;
            addPro_CollectionInput.UserID = UserID;
            this.CreateService<IPro_CollectionService>().Add(addPro_CollectionInput);
            return this.SuccessMsg();
        }


        public ActionResult Pro_CollectionPageList(Pagination pagination, string UserID)
        {
            PagedData<Pro_CollectionInfo> pagedData = this.CreateService<IPro_CollectionService>().GetPageData(pagination, UserID);
            return this.SuccessData(pagedData);
        }

        public ActionResult SetCart(int ShopID, string UserID, string ProductID, string ProSizeID, int ItemNum )
        {
            int n = 0;            
            if(!string.IsNullOrEmpty(UserID))
            { 
                n = this.CreateService<ICartService>().SetCart(ShopID,ProductID, ProSizeID, ItemNum, UserID);

                int count = this.CreateService<ICartService>().CountByUserID(UserID, ShopID);
                return this.SuccessData(count.ToString());
            }
            else
            {
                return this.FailedMsg("请登录后再添加到购物车");
            }
        }

        /// <summary>
        /// 购物车商品数量
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public ActionResult CartGoodsCount(string UserID,int ShopID)
        {
            int count = 0;
            if (!string.IsNullOrEmpty(UserID))
            {
               count = this.CreateService<ICartService>().CountByUserID(UserID, ShopID);
            }            
            return this.SuccessData(count.ToString());
        }

        public ActionResult CartList(string UserID,int ShopID)
        {
            List<CartInfo> list= this.CreateService<ICartService>().GetCartListItem(UserID, ShopID);
            return this.SuccessData(list);
        }

        [HttpPost]
        public ActionResult CartDelete(string Ids)
        {
            if(!string.IsNullOrEmpty(Ids))
            {
                string[] arr = Ids.Split(',');
                foreach(string s in arr)
                {
                    this.CreateService<ICartService>().Delete(s);
                }
                return this.SuccessData("删除成功");
            }
            else
            {
                return this.FailedMsg("请选择删除项");
            }
        }

        [HttpPost]
        public ActionResult CartUpdate(string id,int num,string UserID,int ShopID)
        {
            if(!string.IsNullOrEmpty(id)&&num>0)
            {
                

                this.CreateService<ICartService>().UpdateCart(id, num);
                this.CreateService<ICartService>().UpdatePromotion(id);

                List<CartInfo> list = this.CreateService<ICartService>().GetCartListItem(UserID, ShopID);
                return this.SuccessData(list);

                //return this.SuccessData("修改成功");
            }
            else
            {
                return this.FailedMsg("数量修改失败");
            }
        }

        [HttpPost]
        public ActionResult CartChecked(string Ids,string UserID)
        {
            if (!string.IsNullOrEmpty(Ids))
            {
                ICartService cartService=  this.CreateService<ICartService>();
                cartService.ClearTempOrder(UserID);

                string[] arr = Ids.Split(',');
                foreach (string s in arr)
                {
                    cartService.CartChecked(s);
                }
                return this.SuccessData("OK");
            }
            else
            {
                return this.FailedMsg("请选择要下单的项目");
            }
        }

        public ActionResult CartTempOrder(string UserID)
        {
            List<CartInfo> list = this.CreateService<ICartService>().GetTempOrderItem(UserID);
            return this.SuccessData(list);
        }

        //public ActionResult SmsCode(string phone)
        //{
        //    /*
        //    IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAIVS6lSGKxMTCK", "SCirgtScCx5Veir75bLGzpeAix3jmK");
        //    DefaultAcsClient client = new DefaultAcsClient(profile);
            
        //    string code = AceUtils.GenerateRandomNumber(4);
        //    // 构造请求
        //    CommonRequest request = new CommonRequest();

        //    request.Method = Aliyun.Acs.Core.Http.MethodType.POST;
        //    request.Domain = "dysmsapi.aliyuncs.com";
        //    request.Version = "2017-05-25";
        //    request.Action = "SendSms";

        //    request.RegionId = "cn-hangzhou";
        //    request.QueryParameters.Add("PhoneNumbers", phone);
        //    request.QueryParameters.Add("SignName", "添道营销");
        //    request.QueryParameters.Add("TemplateCode", "SMS_86660148");
        //    request.QueryParameters.Add("TemplateParam", "{\"number\":\"" + code + "\"}");

        //    CommonResponse response = client.GetCommonResponse(request);
           
        //    if (response.Data.Contains("OK"))
        //    {
        //        HttpContext.Session.SetString(Ace.Globals.SmsCode, code);
        //        return this.SuccessData("验证码发送成功" + code);
        //    }
        //    else
        //    {
        //        return this.FailedMsg("验证码发送失败" + code);
        //    }
        //     */

        //    IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", "LTAIuBJ2qrsk6kYQ", "oCFLtdBquRVZPDjYFE7oEhVn5ZABKk");
        //    DefaultAcsClient client = new DefaultAcsClient(profile);
        //    //try
        //    //{
        //    string code = AceUtils.GenerateRandomNumber(4);
        //    // 构造请求
        //    CommonRequest request = new CommonRequest();

        //    request.Method = Aliyun.Acs.Core.Http.MethodType.POST;
        //    request.Domain = "dysmsapi.aliyuncs.com";
        //    request.Version = "2017-05-25";
        //    request.Action = "SendSms";

        //    request.RegionId = "cn-hangzhou";
        //    request.QueryParameters.Add("PhoneNumbers", phone);
        //    request.QueryParameters.Add("SignName", "宅享优快");
        //    request.QueryParameters.Add("TemplateCode", "SMS_162450850");
        //    request.QueryParameters.Add("TemplateParam", "{\"code\":\"" + code + "\"}");

        //    CommonResponse response = client.GetCommonResponse(request);
        //    //SmsResult smsResult= Ace.JsonHelper.Deserialize<SmsResult>(response.Data);

        //    if (response.Data.Contains("OK"))
        //    {
        //        HttpContext.Session.SetString(Ace.Globals.SmsCode, code);
        //        return this.SuccessData("验证码发送成功" );
        //    }
        //    else
        //    {
        //        return this.FailedMsg("验证码发送失败");
        //    }

        //    //}
        //    //catch (ServerException ex)
        //    //{
        //    //    return this.FailedMsg(ex.ToString());
        //    //}
        //    //catch (ClientException ex)
        //    //{
        //    //    return this.FailedMsg(ex.ToString());
        //    //}
        //}


        public ActionResult SmsCodeMX(string phone)
        {
            if (!string.IsNullOrEmpty(phone))
            {
                string code = AceUtils.GenerateRandomNumber(4);
                string Contents = "【泰吉汽配】验证码"+ code;

                bool f = Ace.SMSHelper.SendMsg(phone, Contents, "");
                if (f)
                {
                    HttpContext.Session.SetString(Ace.Globals.SmsCode, code);
                    return this.SuccessMsg();
                }
                else
                {
                    return this.FailedMsg("短信群发失败");
                }
            }
            else
            {
                return this.FailedMsg("请输入手机号码和内容");
            }
        }


        public ActionResult SmsCode(string phone)
        {
            //必填,请参考"开发准备"获取如下数据,替换为实际值
            string apiAddress = "https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1"; //APP接入地址+接口访问URI
            string appKey = "ZPrwe6c63hHI2y43I5ibxFY79dS1"; //APP_Key
            string appSecret = "d3Gsote8S4TwJtY4lKcV08UJ5T5g"; //APP_Secret
            string sender = "8820122034292";// "csms12345678"; //国内短信签名通道号或国际/港澳台短信通道号
            string templateId = "3fd7b9bdd84243ab91f09546ecb8cbd5"; //模板ID

            //条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
            //国际/港澳台短信不用关注该参数
            string signature = "泰祥汽配"; //签名名称

            //必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔
            //string receiver = "+8615123456789,+8615234567890"; //短信接收人号码

            //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
            string statusCallBack = "";

            /*
             * 选填,使用无变量模板时请赋空值 string templateParas = "";
             * 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
             * 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
             * 模板中的每个变量都必须赋值，且取值不能为空
             * 查看更多模板和变量规范:产品介绍>模板和变量规范
             */
            string code = AceUtils.GenerateRandomNumber(4);
            string templateParas = "[\""+ code + "\"]"; //模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。

            try
            {
                //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
                HttpClient client = new HttpClient();
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                //请求Headers
                client.DefaultRequestHeaders.Add("Authorization", "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"");
                client.DefaultRequestHeaders.Add("X-WSSE", BuildWSSEHeader(appKey, appSecret));
                //请求Body
                var body = new Dictionary<string, string>() {
                    {"from", sender},
                    {"to", "+86"+phone},
                    {"templateId", templateId},
                    {"templateParas", templateParas},
                    {"statusCallback", statusCallBack},
                    {"signature", signature} //使用国内短信通用模板时,必须填写签名名称
                };

                HttpContent content = new FormUrlEncodedContent(body);

                var response = client.PostAsync(apiAddress, content).Result;
                //Console.WriteLine(response.StatusCode); //打印响应结果码
                var res = response.Content.ReadAsStringAsync().Result;
                //Console.WriteLine(res); //打印响应信息

                HttpContext.Session.SetString(Ace.Globals.SmsCode, code);
                return this.SuccessData("验证码发送成功");
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.StackTrace);
                //Console.WriteLine(e.Message);
                return this.FailedMsg("验证码发送失败");
            }

            
        }

        /// <summary>
        /// 构造X-WSSE参数值
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        static string BuildWSSEHeader(string appKey, string appSecret)
        {
            string now = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); //Created
            string nonce = Guid.NewGuid().ToString().Replace("-", ""); //Nonce

            byte[] material = Encoding.UTF8.GetBytes(nonce + now + appSecret);
            byte[] hashed = SHA256Managed.Create().ComputeHash(material);
            string hexdigest = BitConverter.ToString(hashed).Replace("-", "");
            string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(hexdigest)); //PasswordDigest

            return String.Format("UsernameToken Username=\"{0}\",PasswordDigest=\"{1}\",Nonce=\"{2}\",Created=\"{3}\"",
                            appKey, base64, nonce, now);
        }

        /// <summary>
        /// 构造请求body
        /// </summary>
        /// <param name="keyValues"></param>
        /// <returns></returns>
        static string BuildQueryString(NameValueCollection keyValues)
        {
            StringBuilder temp = new StringBuilder();
            foreach (string item in keyValues.Keys)
            {
                temp.Append(item).Append("=").Append(HttpUtility.UrlEncode(keyValues.Get(item))).Append("&");
            }
            return temp.Remove(temp.Length - 1, 1).ToString();
        }


        public ActionResult SimpleLogin(string OpenID,decimal GPS_X=0,decimal GPS_Y=0)
        {
            if(!string.IsNullOrEmpty(OpenID))
            {
                Users users = this.CreateService<IUsersService>().GetModelByOpenID(OpenID);
                if (users != null)
                {
                    if(GPS_X>0&&GPS_Y>0)
                    {
                        AddUsers_SecurityInput m = new AddUsers_SecurityInput();
                        m.GPS_X = GPS_X;
                        m.GPS_Y = GPS_Y;
                        m.CreateDate = DateTime.Now;
                        m.UserID = users.Id;
                        this.CreateService<IUsers_SecurityService>().Add(m);
                    }

                    return this.SuccessData(users);
                }
                else
                {
                    return this.FailedMsg("请先注册");
                }
            }
            else
            {
                return this.FailedMsg("无法获取OpenID");
            }
            
        }
        
        public ActionResult CheckOpenID(string OpenID)
        {
            if(!string.IsNullOrEmpty(OpenID))
            {
                var US = this.CreateService<IUsersService>();
                Users users = US.GetModelByOpenID(OpenID);
                if (users != null)
                {
                    return this.SuccessData(users);
                }
                else
                {
                    return this.FailedMsg("没有注册");
                }
            }
            else
            {
                return this.FailedMsg("无法获取OpenID");
            }
        }

         

        public ActionResult AddressDetail(string Id)
        {
            if(!string.IsNullOrEmpty(Id))
            {
                Users_AddressInfo users_Address = this.CreateService<IUsers_AddressService>().GetModel(Id);
                return this.SuccessData(users_Address);
            }
            else
            {
                return this.FailedMsg("参数缺失");
            }
        }
        [HttpGet]
        public ActionResult AddressList(string UserID)
        {
            if (!string.IsNullOrEmpty(UserID))
            {
                List<Users_AddressInfo> list = this.CreateService<IUsers_AddressService>().GetList(UserID);
                return this.SuccessData(list);
            }
            else
            {
                return this.FailedMsg("参数缺失");
            }
        }

        [HttpPost]
        public ActionResult AdressAdd(AddUsers_AddressInput input)
        {
            this.CreateService<IUsers_AddressService>().Add(input);
            return this.SuccessData("OK");
        }

        [HttpPost]
        public ActionResult AdressUpdate(UpdateUsers_AddressInput input)
        {
            this.CreateService<IUsers_AddressService>().Update(input);
            return this.SuccessData("OK");
        }

        public ActionResult AddressDelete(string id)
        {
            this.CreateService<IUsers_AddressService>().Delete(id);
            return this.SuccessData("OK");
        }

        public ActionResult AddressDefault(string UserID)
        {
            Users_AddressInfo modle = this.CreateService<IUsers_AddressService>().GetDefaultAddress(UserID);
            if(modle!=null)
            {
                return this.SuccessData(modle);
            }
            else
            {
                return this.FailedMsg();
            }
        }

       [HttpPost]
        public ActionResult OrderSubmit(string UserID, string AddressID,int ShopID,string remark="", string express_name ="",string UserPass="")
        {
            if(string.IsNullOrEmpty(UserPass))
            {
                return this.FailedMsg("请输入支付密码");
            }

            string Md5Pass = Ace.Security.PasswordHelper.Md5String(UserPass);
            Users userInfo = this.CreateService<IUsersService>().GetModel(UserID);
            if(userInfo.UserPass!=Md5Pass)
            {
                return this.FailedMsg("您输入的支付密码错误");
            }

            IUsersChargeService chargeService = this.CreateService<IUsersChargeService>();
            IShopOrderService orderService = this.CreateService<IShopOrderService>();
            decimal Left = chargeService.GetLeft(UserID);
            if(Left<0)
            {
                return this.FailedMsg("账户余额不足，不能下单");
            }

            //List<Sort> sort_list = this.CreateService<ISortService>().GetList(25);
            //string express_name = sort_list[express_index].Title;

            
            string n = orderService.SubmitOrder(UserID, AddressID, ShopID, remark, express_name);
            if(!string.IsNullOrEmpty(n))
            {
                ShopOrder order = orderService.GetModel(n);

                //生成余额支付记录
                string ChargeCode = "WH" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                AddUsersChargeInput input = new AddUsersChargeInput();
                input.Balance = 0;
                input.ChargeCode = ChargeCode;
                input.ChargeSort = 0;// 消费0 1充值
                input.Title = "消费";
                input.ChargeTotal = order.Total;
                input.CreateDate = DateTime.Now;
                input.CreateID = "0";
                input.ImageUrl = "";
                input.UserID = UserID;
                UsersCharge NewCharge = chargeService.Add(input);

                //更新余额账单信息到订单表
                orderService.UpdateOrderCharge(n,1, ChargeCode, NewCharge.Id);
            }
            else
            {
                return this.FailedMsg("订单提交失败");
            }
            

            return this.SuccessData(n);
        }


        public ActionResult OrderSubmit_debug(string UserID, string AddressID, int ShopID, string remark = "", string express_name = "")
        {
            string n = this.CreateService<IShopOrderService>().SubmitOrder(UserID, AddressID, ShopID, remark, express_name);
            return this.SuccessData(n);
        }


        [HttpPost]
        public ActionResult OrderSubmit2(string UserID, string AddressID, int ShopID, string ProductID)
        {
            Product info = this.CreateService<IProductService>().GetModle(ProductID);
            if(info.Stock>1)
            {
                string new_order_id = "";
                string n = this.CreateService<IShopOrderService>().SubmitOrder2(UserID, AddressID, ShopID, ProductID,out new_order_id);
                if (n == "领取成功")
                {
                    ShopOrder order = this.CreateService<IShopOrderService>().GetModel(new_order_id);

                    Users usersInfo = this.CreateService<IUsersService>().GetModel(UserID);

                    //领取会员专享  用户
                    string post_data = "{\"data\":{\"character_string1\":{\"value\":\"" + order.OrderCode + "\"},\"amount2\":{\"value\":\"" + order.Total.ToString() + "\"},\"date3\":{\"value\":\"" + order.CreateDate.ToString("yyyy-MM-dd HH:mm") + "\"},\"thing4\":{\"value\":\"您已成功领取会员专享产品！商家尽快为你安排服务。\"} },\"template_id\":\"Mro6voIQn6DT6YRbMJRZLJZJyPyzzs2hSvcYGhuKVyg\",\"touser\":\"" + usersInfo.OpenID + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/start/index\"}";
                    string rs1= SendSubscribeMessage(usersInfo.OpenID, post_data);

                    this.CreateService<IALogService>().AddLog("领取会员专享产品通知用户", post_data, rs1);

                    //领取会员专享  商家
                    string AdminOpenID = Globals.Configuration["AppSettings:AdminOpenID"].ToString();
                    if (string.IsNullOrEmpty(AdminOpenID))
                    {
                        AdminOpenID = "o-TSC4ifbn2Fkw7PnwzCegQhpf5Y";
                    }
                    string post_data2 = "{\"data\":{\"character_string1\":{\"value\":\"" + order.OrderCode + "\"},\"amount2\":{\"value\":\"" + order.Total.ToString() + "\"},\"date3\":{\"value\":\"" + order.CreateDate.ToString("yyyy-MM-dd HH:mm") + "\"},\"thing4\":{\"value\":\"用户领取会员专享产品！请尽快安排服务。\"} },\"template_id\":\"Mro6voIQn6DT6YRbMJRZLJZJyPyzzs2hSvcYGhuKVyg\",\"touser\":\"" + AdminOpenID + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/start/index\"}";
                    string rs2 = SendSubscribeMessage(AdminOpenID, post_data2);

                    this.CreateService<IALogService>().AddLog("领取会员专享产品通知商家", post_data2, rs2);

                    return this.SuccessMsg(n);
                }
                else
                {
                    return this.FailedMsg(n);
                }
            }
            else
            {
                return this.FailedMsg("库存不足，无法领取");
            }
            
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="CreateID"></param>
        /// <returns></returns>
        public ActionResult OrderList(Pagination pagination, string UserID)
        {
            PagedData<ShopOrderInfo2> pagedData = this.CreateService<IShopOrderService>().GetPageData(pagination, UserID);
            return this.SuccessData(pagedData);
        }

        public ActionResult OrderDetail(string id)
        {
            ShopOrderInfo2 info = new ShopOrderInfo2();
            ShopOrder modle = this.CreateService<IShopOrderService>().GetModel(id);
            info.AddressID = modle.AddressID;
            info.AddressInfo = this.CreateService<IUsers_AddressService>().GetModel(modle.AddressID);
            info.AuthID = "";
            info.CreateDate = modle.CreateDate;
            info.CreateID = "";
            info.Freight = modle.Freight;
            info.Id = modle.Id;
            info.OrderCode = modle.OrderCode;
            info.OrderItem = this.CreateService<IShopOrderItemService>().GetOrderItemList(modle.Id);
            info.ProTotal = modle.ProTotal;
            info.ST = modle.ST;
            info.STName = this.CreateService<IShopOrderService>().GetST_Name(modle.ST);
            info.Total = modle.Total;
            info.UpdateTime = modle.UpdateTime;

            info.express_code = modle.express_code;
            info.express_name = modle.express_name;
            info.remark = modle.remark;
            info.PaySort = modle.PaySort;
            info.ChargeCode = modle.ChargeCode;
            info.ChargeID = modle.ChargeID;
            info.PromotionTotal = modle.PromotionTotal;

            return this.SuccessData(info);
        }

        public ActionResult OrderCancel(string id,int st)
        {
            if(!string.IsNullOrEmpty(id))
            {
                IShopOrderService orderService= this.CreateService<IShopOrderService>();
                ShopOrder order = orderService.GetModel(id);

                if(order.ST==0|| order.ST == 1)
                {
                    int n = orderService.UpdateOrderStatus(id, st);
                    if (n > 0)
                    {

                        //if (!string.IsNullOrEmpty(order.transaction_id))
                        //{
                        //    Logger logger = LogManager.GetLogger("OrderCancel：" + id);

                        //    if (!string.IsNullOrEmpty(order.transaction_id) && !string.IsNullOrEmpty(order.OrderCode))
                        //    {
                        //        string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
                        //        string mch_id = Globals.Configuration["AppSettings:TenPayV3_MchId"].ToString();
                        //        string appid = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
                        //        string nonce_str = TenPayV3Util.GetNoncestr();
                        //        string transaction_id = order.transaction_id;
                        //        string out_trade_no = order.OrderCode;
                        //        string out_refund_no = IdHelper.CreateStringSnowflakeId();
                        //        int total_fee = Convert.ToInt32(order.Total * 100);
                        //        int refund_fee = Convert.ToInt32(order.Total * 100);

                        //        string notify_url = Globals.Configuration["AppSettings:FileDomain"].ToString() + "/API/ReFundNotify";

                        //        var dataInfo = new TenPayV3RefundRequestData(appid, mch_id, TenPayV3_Key,
                        //        null, nonce_str, null, out_trade_no, out_refund_no, total_fee, refund_fee, mch_id, null, notifyUrl: notify_url);
                        //        var cert = @"D:\cert\apiclient_cert.p12";//根据自己的证书位置修改
                        //        var password = mch_id;//默认为商户号，建议修改
                        //        var result = TenPayV3.Refund(dataInfo, cert, password);
                        //        //return Content(string.Format("退款结果：{0} {1}。您可以刷新当前页面查看最新结果。", result.result_code, result.err_code_des));
                        //        if (result.result_code == "SUCCESS")
                        //        {
                        //            this.CreateService<IShopOrderService>().UpdateReFundStatu(order.OrderCode, out_refund_no, "");
                        //            //return this.SuccessMsg("退款申请已提交");
                        //            logger.Info("退款申请已提交");
                        //        }
                        //        else
                        //        {
                        //            logger.Info(result.err_code + "," + result.err_code_des);
                        //        }
                        //    }
                        //    else
                        //    {
                        //        logger.Info("未付款订单");
                        //    }
                        //}
                        return this.SuccessData("OK");
                    }
                    else
                    {
                        return this.FailedMsg("订单不存在");
                    }

                    
                }
                else
                {
                    return this.FailedMsg("已发货，不能取消订单");
                }
            }
            else
            {
                return this.FailedMsg("参数缺失");
            }
        }

        public ActionResult ProCollectionList(string UserID)
        {
            List<Pro_CollectionInfo> list = this.CreateService<IPro_CollectionService>().GetList(UserID);
            return this.SuccessData(list);
        }

        public ActionResult CollectDelete(string id)
        {
            this.CreateService<IPro_CollectionService>().Delete(id);
            return this.SuccessData("OK");
        }

        public ActionResult CollectAdd(string UserID,string ProductID)
        {
            IPro_CollectionService pro_CollectionService = this.CreateService<IPro_CollectionService>();
            int count = pro_CollectionService.Count(UserID, ProductID);
            if(count==0)
            {
                AddPro_CollectionInput input = new AddPro_CollectionInput();
                input.CreateDate = DateTime.Now;
                input.ProductID = ProductID;
                input.UserID = UserID;
                pro_CollectionService.Add(input);
            }
            else
            {
                pro_CollectionService.Delete(UserID, ProductID);
            }
            return this.SuccessData("OK");
        }

        /// <summary>
        /// 浏览记录
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public ActionResult ProductRcdList(Pagination pagination,string UserID)
        {
            PagedData<Product_rcdInfo> list = this.CreateService<IProduct_rcdService>().GetPageList(pagination, UserID);
            return this.SuccessData(list);
        }


        public ActionResult ProductRcdAdd(string UserID, string ProductID)
        {
            IProduct_rcdService product_RcdService = this.CreateService<IProduct_rcdService>();
            Product_rcd modle = product_RcdService.GetModel(UserID, ProductID);
            if(modle==null)
            {
                AddProduct_rcdInput input = new AddProduct_rcdInput();
                input.CreateDate = DateTime.Now;
                input.Hit = 1;
                input.ProductID = ProductID;
                input.UpdateTime = DateTime.Now;
                input.UserID = UserID;
                product_RcdService.Add(input);
            }
            else
            {
                product_RcdService.UpdateHit(modle.Id, modle.Hit + 1);
            }
            return this.SuccessData("OK");
        }

        public ActionResult ProductRcdDelete(string id)
        {
            this.CreateService<IProduct_rcdService>().Delete(id);
            return this.SuccessData("OK");
        }

        public ActionResult Users_SecurityList(Pagination pagination, string UserID)
        {
            PagedData<Users_SecurityInfo> list = this.CreateService<IUsers_SecurityService>().GetPageData(pagination, UserID);
            return this.SuccessData(list);
        }

        [HttpPost]
        public ActionResult FeedbackAdd(string Summary,int SortID,string Mobile,string UserID,string SortName)
        {
            AddNewsInput input = new AddNewsInput();
            input.Contents = "";
            input.CreateDate = DateTime.Now;
            input.CreateID = UserID;
            input.ImageUrl = "";
            input.IsValid = 0;
            input.LinkUrl = Mobile;
            input.SortID = SortID;
            input.Summary = Summary;
            input.Title = SortName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            this.CreateService<INewsService>().Add(input);
            return this.SuccessData("OK");
        }


        public ActionResult SearchIndex()
        {
            return this.SuccessData(new { historyKeywordList="增压器;传感器", defaultKeyword = "增压器", hotKeywordList = "增压器;传感器" });
        }

        public ActionResult SearchHelper(string keyword, int ShopID)
        {
            if (!string.IsNullOrEmpty(keyword))
            {
                List<ProductSearchKey> list = this.CreateService<IProductService>().GetSearchKeys(keyword, ShopID);
                return this.SuccessData(list);
            }
            else
            {
                return this.FailedMsg();
            }
        }

        public ActionResult UpdateOrderStatus(string id,int ST=0,string prepay_id="",string openId="")
        {
            this.CreateService<IShopOrderService>().UpdateOrderStatus(id, 1);
            if(!string.IsNullOrEmpty(prepay_id) &&!string.IsNullOrEmpty(openId) )
            {
                ShopOrder order = this.CreateService<IShopOrderService>().GetModel(id);

                string pro_cont = string.Empty;
                List<ShopOrderItemInfo> list= this.CreateService<IShopOrderItemService>().GetOrderItemList(id);
                foreach(var item in list)
                {
                    pro_cont += item.ProductName + "(数量:" + item.ItemNum + ")";
                }

                Shop shop = this.CreateService<IShopService>().GetModel(order.ShopID);

                

                string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
                var data = new
                {
                    keyword1 = new TemplateDataItem(order.Total.ToString()),//订单金额
                    keyword2 = new TemplateDataItem("已付款"),
                    keyword3 = new TemplateDataItem(order.OrderCode),
                    keyword4 = new TemplateDataItem(pro_cont),
                    keyword5 = new TemplateDataItem(order.CreateDate.ToString("yyyy-MM-dd HH:mm")),
                    keyword6 = new TemplateDataItem(shop.ShopName),
                    keyword7 = new TemplateDataItem(shop.ShopAddress),
                    keyword8 = new TemplateDataItem(shop.ShopTel)
                };

                var tmResult = Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.SendTemplateMessage(WxOpenAppId, openId, "83MxvljD9qeLsjG133X9FpTix08jWPHCq29242h8loM", data, prepay_id, "pages/websocket/websocket", "websocket",
                         null);
            }
            return this.SuccessData("OK");
        }

        //---------------------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="OpenId"></param>
        /// <param name="OrderID"></param>
        /// <returns></returns>
        public ActionResult GetPrepayid(string OpenId, string OrderID)
        {
            //try
            //{
                ShopOrder shopOrder = this.CreateService<IShopOrderService>().GetModel(OrderID);


                string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
                string WxOpenAppSecret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();
                string TenPayV3_MchId = Globals.Configuration["AppSettings:TenPayV3_MchId"].ToString();
                string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
                string TenpayNotify = Globals.Configuration["AppSettings:TenpayNotify"].ToString();


                //生成订单10位序列号，此处用时间和随机数生成，商户根据自己调整，保证唯一
                //var sp_billno = DateTime.Now.ToString("yyyyMMddHHmm") + TenPayV3Util.BuildRandomStr(6);
                var sp_billno = shopOrder.OrderCode;
                string attach = shopOrder.CreateID + "|" + OpenId + "|" + OrderID + "|" + sp_billno;

                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr = TenPayV3Util.GetNoncestr();
                var ip = "124.70.155.127";//HttpContext.GetClientIP();//


                var body = "订单号：" + shopOrder.OrderCode;
                var price = Convert.ToInt32(shopOrder.Total * 100);//  1;//单位：分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WxOpenAppId, TenPayV3_MchId, body, sp_billno,
                    price, ip, TenpayNotify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, OpenId, TenPayV3_Key, nonceStr, null, null, null,"", attach);

                var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口

                //WeixinTrace.SendCustomLog("统一订单接口调用结束", "请求：\r\n\r\n" + xmlDataInfo.ToJson() + "\r\n\r\n返回结果：\r\n\r\n" + result.ToJson());
                //Logger logger = LogManager.GetLogger("SimpleDemo");
                //logger.Info("\r\n\r\n*********************************************************************\r\n\r\n");
                //logger.Info("\r\n\r\n" + xmlDataInfo.ToJson()+"\r\n\r\n" );
                //logger.Info("\r\n\r\n*********************************************************************\r\n\r\n");
                //logger.Info("\r\n\r\n" + result.ToJson()+ "\r\n\r\n");

                var packageStr = "prepay_id=" + result.prepay_id;

                
                return Json(new
                {
                    success = true,
                    prepay_id = result.prepay_id,
                    appId = WxOpenAppId,
                    timeStamp,
                    nonceStr,
                    package = packageStr,
                    signType = "MD5",
                    paySign = TenPayV3.GetJsPaySign(WxOpenAppId, timeStamp, nonceStr, packageStr, TenPayV3_Key)
                });
            //}
            //catch (Exception ex)
            //{
            //    return Json(new
            //    {
            //        success = false,
            //        msg = ex.Message
            //    });
            //}

        }


        public ActionResult PayNotifyUrl()
        {
            //try
            //{

            Logger logger = LogManager.GetLogger("SimpleDemo");
            logger.Info("\r\n\r\n*********************************************************************\r\n\r\n");

            

            string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
            ResponseHandler resHandler = new ResponseHandler(HttpContext);

            string return_code = resHandler.GetParameter("return_code");
            string return_msg = resHandler.GetParameter("return_msg");

            logger.Info("\r\n\r\n return_code:" + return_code + "\r\n\r\n");
            logger.Info("\r\n\r\n return_code:" + return_msg + "\r\n\r\n");


            string res = null;

            resHandler.SetKey(TenPayV3_Key);
            //验证请求是否从微信发过来（安全）
            if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
            {
                res = "success";//正确的订单处理
                //直到这里，才能认为交易真正成功了，可以进行数据库操作，但是别忘了返回规定格式的消息！
            }
            else
            {
                res = "wrong";//错误的订单处理
            }

            /* 这里可以进行订单处理的逻辑 */
            string UserID = "";
            string OpenId = "";
            string OrderID = "";
            string sp_billno = "";
            if (res == "success")
            {
                string transaction_id = resHandler.GetParameter("transaction_id");

                string attach = resHandler.GetParameter("attach");
                logger.Info("\r\n\r\n return_code:" + attach + "\r\n\r\n");
                if (!string.IsNullOrEmpty(attach))
                {
                    string[] arr = attach.Split('|');
                    UserID = arr[0];
                    OpenId = arr[1];
                    OrderID = arr[2];
                    sp_billno = arr[3];
                    this.CreateService<IShopOrderService>().UpdateOrderStatus(OrderID, 1, transaction_id);


                    ShopOrder order = this.CreateService<IShopOrderService>().GetModel(OrderID);
                    //订单付款成功通知  用户
                    string post_data = "{\"data\":{\"character_string1\":{\"value\":\""+ order.OrderCode + "\"},\"amount2\":{\"value\":\"" + order.Total.ToString() + "\"},\"date3\":{\"value\":\"" + order.CreateDate.ToString("yyyy-MM-dd HH:mm") + "\"},\"thing4\":{\"value\":\"您已经下单成功！商家尽快为你安排服务。\"} },\"template_id\":\"Mro6voIQn6DT6YRbMJRZLJZJyPyzzs2hSvcYGhuKVyg\",\"touser\":\"" + OpenId + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/start/index\"}";
                    string rs1 = SendSubscribeMessage(OpenId, post_data);

                    this.CreateService<IALogService>().AddLog("用户下单支付成功通知用户", post_data, rs1);

                    //订单付款成功通知  商家
                    string AdminOpenID = Globals.Configuration["AppSettings:AdminOpenID"].ToString();
                    if(string.IsNullOrEmpty(AdminOpenID))
                    {
                        AdminOpenID = "o-TSC4ifbn2Fkw7PnwzCegQhpf5Y";
                    }
                    string post_data2 = "{\"data\":{\"character_string1\":{\"value\":\"" + order.OrderCode + "\"},\"amount2\":{\"value\":\"" + order.Total.ToString() + "\"},\"date3\":{\"value\":\"" + order.CreateDate.ToString("yyyy-MM-dd HH:mm") + "\"},\"thing4\":{\"value\":\"用户已经下单成功！请尽快安排服务。\"} },\"template_id\":\"Mro6voIQn6DT6YRbMJRZLJZJyPyzzs2hSvcYGhuKVyg\",\"touser\":\"" + AdminOpenID + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/start/index\"}";
                    string rs2 = SendSubscribeMessage(AdminOpenID, post_data2);
                    this.CreateService<IALogService>().AddLog("用户下单支付成功通知商家", post_data2, rs2);


                    //---公众号通知
                    
                    string para = "Title=用户下单支付成功&OrderCode=" + order.OrderCode + "&OrderTime=" + order.CreateDate.ToString("yyyy-MM-dd HH:mm:ss") + "&Remark=用户已经下单成功！请尽快安排服务。";
                    string url = "http://mp.whtxqp.com/AsyncMethods/OrderTemplateMessageTest?"+ para;
                    try
                    {
                        HttpGet(url);
                        this.CreateService<IALogService>().AddLog("用户下单公众号通知", para, "正常");
                    }
                    catch(Exception ee)
                    {
                        this.CreateService<IALogService>().AddLog("用户下单公众号通知异常", para,"异常");
                        logger.Info("\r\n\r\n 用户下单公众号通知异常:" + "", ee.ToString() + "\r\n\r\n");
                    }
                   

                    
                }
            }

            //发送支付成功的模板消息
            //try
            //{
            //        string appId = Config.SenparcWeixinSetting.TenPayV3_AppId;//与微信公众账号后台的AppId设置保持一致，区分大小写。
            //        string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
            //        string openId = resHandler.GetParameter("openid");
            //        var templateData = new WeixinTemplate_PaySuccess("https://weixin.senparc.com", "购买商品", "状态：" + return_code);

            //        Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数", appId + " , " + openId);

            //        var result = Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessage(appId, openId, templateData);

            //        logger.Info("\r\n\r\n 支付成功模板消息 suc:" + "", result.ToJson() + "\r\n\r\n");
            //}
            //catch (Exception ex)
            //{
            //    //Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息", ex.ToString());
            //    logger.Info("\r\n\r\n 支付成功模板消息 err:" + "", ex.ToString() + "\r\n\r\n");
            //}

            var notifyXml = resHandler.ParseXML();

            logger.Info("\r\n\r\n notifyXml:" + "", notifyXml + "\r\n\r\n");
            var logDir = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/TenPayNotify/{0}", SystemTime.Now.ToString("yyyyMMdd")));
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            var logPath = Path.Combine(logDir, string.Format("{0}-{1}-{2}.txt", SystemTime.Now.ToString("yyyyMMdd"), SystemTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8)));
            using (var fileStream = System.IO.File.OpenWrite(logPath))
            {
                //var notifyXml = resHandler.ParseXML();
                //fileStream.Write(Encoding.Default.GetBytes(res), 0, Encoding.Default.GetByteCount(res));

                fileStream.Write(Encoding.Default.GetBytes(notifyXml), 0, Encoding.Default.GetByteCount(notifyXml));
                fileStream.Close();
            }

            string xml = string.Format(@"<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>", return_code, return_msg);
                return Content(xml, "text/xml");
            //}
            //catch (Exception ex)
            //{
            //    WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
            //    throw;
            //}
        }


        public ActionResult PayRefund(string OrderID)
        {
            Logger logger = LogManager.GetLogger("SimpleDemo");

            ShopOrder order = this.CreateService<IShopOrderService>().GetModel(OrderID);
            if (!string.IsNullOrEmpty(order.transaction_id) && !string.IsNullOrEmpty(order.OrderCode))
            {
                string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
                string mch_id = Globals.Configuration["AppSettings:TenPayV3_MchId"].ToString();
                string appid = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
                string nonce_str = TenPayV3Util.GetNoncestr();
                string transaction_id = order.transaction_id;
                string out_trade_no = order.OrderCode;
                string out_refund_no = IdHelper.CreateStringSnowflakeId();
                int total_fee = Convert.ToInt32(order.Total * 100);
                int refund_fee = Convert.ToInt32(order.Total * 100);

                string notify_url = Globals.Configuration["AppSettings:FileDomain"].ToString() + "/API/ReFundNotify";

                var dataInfo = new TenPayV3RefundRequestData(appid, mch_id, TenPayV3_Key,
                null, nonce_str, null, out_trade_no, out_refund_no, total_fee, refund_fee, mch_id, null, notifyUrl: notify_url);
                var cert = @"D:\cert\apiclient_cert.p12";//根据自己的证书位置修改
                var password = mch_id;//默认为商户号，建议修改
                var result = TenPayV3.Refund(dataInfo, cert, password);
                //return Content(string.Format("退款结果：{0} {1}。您可以刷新当前页面查看最新结果。", result.result_code, result.err_code_des));
                if (result.result_code == "SUCCESS")
                {
                    this.CreateService<IShopOrderService>().UpdateReFundStatu(order.OrderCode, out_refund_no, "");
                    //return this.SuccessMsg("退款申请已提交");
                    logger.Info("退款申请已提交");
                    return this.SuccessData("退款申请已提交");
                }
                else
                {
                    logger.Info(result.err_code + "," + result.err_code_des);
                    return this.SuccessData(result.err_code + "," + result.err_code_des);
                }
            }
            else
            {
                logger.Info("未付款订单");
                return this.SuccessData("未付款订单");
            }
        }


        public ActionResult ReFundNotify()
        {
            //try
            //{
            WeixinTrace.Log("----------------------------PayNotifyUrl-----------------------------------------------");
            Logger logger = LogManager.GetLogger("SimpleDemo");
            logger.Info("\r\n\r\n*********************************************************************\r\n\r\n");



            string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
            ResponseHandler resHandler = new ResponseHandler(HttpContext);

            string return_code = resHandler.GetParameter("return_code");
            string return_msg = resHandler.GetParameter("return_msg");

            logger.Info("\r\n\r\n return_code:" + return_code + "\r\n\r\n");
            logger.Info("\r\n\r\n return_code:" + return_msg + "\r\n\r\n");


            string res = null;
            //resHandler.SetKey(TenPayV3_Key);
            //验证请求是否从微信发过来（安全）
            if (return_code.ToUpper() == "SUCCESS")
            {
                res = "success";//正确的订单处理

            }
            else
            {
                res = "wrong";//错误的订单处理
            }

            if (res == "success")
            {
                string req_info = resHandler.GetParameter("req_info");

                string ext_info = Senparc.Weixin.TenPay.V3.TenPayV3Util.DecodeRefundReqInfo(req_info, TenPayV3_Key);
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(ext_info);
                string xml_out_refund_no = doc.SelectSingleNode("/root/out_refund_no").InnerText;//商户退款单号
                string xml_refund_status = doc.SelectSingleNode("/root/refund_status").InnerText;//退款状态
                string xml_out_trade_no = doc.SelectSingleNode("/root/out_trade_no").InnerText;//退款状态


                /*
                 退款状态
                SUCCESS—退款成功
                REFUNDCLOSE—退款关闭。
                PROCESSING—退款处理中
                CHANGE—退款异常，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，可前往商户平台（pay.weixin.qq.com）-交易中心，手动处理此笔退款。
                 */

                this.CreateService<IShopOrderService>().UpdateReFundStatu(xml_out_trade_no, "", xml_refund_status);
                this.CreateService<IRefundService>().UpdateReFundStatu(xml_out_refund_no, xml_refund_status);

                logger.Info("\r\n\r\n “" + xml_refund_status + "”:\r\n\r\n");
            }
            else
            {
                logger.Info("\r\n\r\n 退款异常:\r\n\r\n");
            }

            var notifyXml = resHandler.ParseXML();
            logger.Info("\r\n\r\n notifyXml:" + "", notifyXml + "\r\n\r\n");

            string xml = string.Format(@"<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>", return_code, return_msg);
            return Content(xml, "text/xml");

            //return this.SuccessMsg();
        }

        //--------------------------------------------------------------------会员充值-------------------------------------------------------------------------------
        /// <summary>
        /// 会员充值
        /// </summary>
        /// <param name="OpenId"></param>
        /// <param name="OrderID"></param>
        /// <returns></returns>
        public ActionResult GetRolePrepayid(string OpenId,int RoleID,string UserID,int Days,decimal Fee,string Title)
        {
            //try
            //{
            //Users_Role  role = this.CreateService<IUsers_RoleService>().GetModel(RoleID);
            Users userInfo=  this.CreateService<IUsersService>().GetModel(UserID);


            string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
            string WxOpenAppSecret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();
            string TenPayV3_MchId = Globals.Configuration["AppSettings:TenPayV3_MchId"].ToString();
            string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
            string TenpayNotify = Globals.Configuration["AppSettings:FileDomain"].ToString()+ "/API/PayRoleNotifyUrl";


            int price = Convert.ToInt32(Fee * 100);//单位：分

            //生成订单10位序列号，此处用时间和随机数生成，商户根据自己调整，保证唯一
            var sp_billno = DateTime.Now.ToString("yyyyMMddHHmm") + TenPayV3Util.BuildRandomStr(6);
            //var sp_billno = userInfo.Id;
            string attach = UserID + "|" + OpenId + "|" + RoleID+"|"+ sp_billno+"|"+ price+"|"+ Days+"|"+ Title;

            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonceStr = TenPayV3Util.GetNoncestr();
            var ip = "124.70.155.127";//HttpContext.GetClientIP();//


            var body = Title+"会员充值" ;
            
            var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WxOpenAppId, TenPayV3_MchId, body, sp_billno,
                price, ip, TenpayNotify, Senparc.Weixin.TenPay.TenPayV3Type.JSAPI, OpenId, TenPayV3_Key, nonceStr,"",null,null, Title, attach);

            var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口
            
            var packageStr = "prepay_id=" + result.prepay_id;


            return Json(new
            {
                success = true,
                prepay_id = result.prepay_id,
                appId = WxOpenAppId,
                timeStamp,
                nonceStr,
                package = packageStr,
                signType = "MD5",
                paySign = TenPayV3.GetJsPaySign(WxOpenAppId, timeStamp, nonceStr, packageStr, TenPayV3_Key)
            });
            //}
            //catch (Exception ex)
            //{
            //    return Json(new
            //    {
            //        success = false,
            //        msg = ex.Message
            //    });
            //}

        }


        public ActionResult PayRoleNotifyUrl()
        {
            //try
            //{

            Logger logger = LogManager.GetLogger("SimpleDemo");
            logger.Info("\r\n\r\n*********************************************************************\r\n\r\n");

            string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
            ResponseHandler resHandler = new ResponseHandler(HttpContext);

            string return_code = resHandler.GetParameter("return_code");
            string return_msg = resHandler.GetParameter("return_msg");

            logger.Info("\r\n\r\n return_code:" + return_code + "\r\n\r\n");
            logger.Info("\r\n\r\n return_code:" + return_msg + "\r\n\r\n");


            string res = null;

            resHandler.SetKey(TenPayV3_Key);
            //验证请求是否从微信发过来（安全）
            if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
            {
                res = "success";//正确的订单处理
                //直到这里，才能认为交易真正成功了，可以进行数据库操作，但是别忘了返回规定格式的消息！
            }
            else
            {
                res = "wrong";//错误的订单处理
            }

            /* 这里可以进行订单处理的逻辑 */
            string attach = "";
            string UserID = "";
            string OpenId = "";
            string RoleID = "";
            string out_trade_no = "";
            string price = "";
            string Days = "";
            string Title = "";
            if (res == "success")
            {
                string transaction_id = resHandler.GetParameter("transaction_id");
                double total_fee=Convert.ToDouble(resHandler.GetParameter("total_fee"));
                

                attach = resHandler.GetParameter("attach");
                logger.Info("\r\n\r\n return_code:" + attach + "\r\n\r\n");
                if (!string.IsNullOrEmpty(attach))
                {
                    string[] arr = attach.Split('|');
                    UserID = arr[0];
                    OpenId = arr[1];
                    RoleID = arr[2];
                    out_trade_no = arr[3];
                    price= arr[4];
                    Days= arr[5];
                    Title = arr[6];

                    double total_fee2 = Convert.ToDouble(total_fee / 100);
                    decimal total_fee3 = Convert.ToDecimal(total_fee2);

                    //充值成功自动设置会员等级
                    int day_span = Convert.ToInt32(Days);
                    this.CreateService<IUsersService>().UpdateUserRole(UserID,int.Parse(RoleID), transaction_id, out_trade_no, day_span);
                     
                    this.CreateService<IUsersPayService>().Add(new AddUsersPayInput { Title= Title,  RoleID =Convert.ToInt32(RoleID), expire_date = DateTime.Now.AddDays(day_span), transaction_date = DateTime.Now, transaction_id = transaction_id, transaction_price = total_fee3, UserID = UserID, out_trade_no= out_trade_no });

                    Users usersInfo = this.CreateService<IUsersService>().GetModel(UserID);

                    //会员充值  通知用户
                    string post_data = "{\"data\":{\"phone_number2\":{\"value\":\"" + usersInfo.Mobile + "\"},\"thing1\":{\"value\":\""+ Title + "充值成功\"} },\"template_id\":\"cXwNPR9BH1miAeJz3hBYL06zSE19i4SSq0u_eZ195N8\",\"touser\":\"" + OpenId + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/start/index\"}";
                    string rs1 = SendSubscribeMessage(OpenId, post_data);
                    this.CreateService<IALogService>().AddLog("会员充值通知用户", post_data, rs1);

                    //会员充值  通知商家
                    string AdminOpenID = Globals.Configuration["AppSettings:AdminOpenID"].ToString();
                    if (string.IsNullOrEmpty(AdminOpenID))
                    {
                        AdminOpenID = "o-TSC4ifbn2Fkw7PnwzCegQhpf5Y";
                    }
                    string post_data2 = "{\"data\":{\"phone_number2\":{\"value\":\"" + usersInfo.Mobile + "\"},\"thing1\":{\"value\":\"" + Title + "充值成功\"} },\"template_id\":\"cXwNPR9BH1miAeJz3hBYL06zSE19i4SSq0u_eZ195N8\",\"touser\":\"" + AdminOpenID + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/start/index\"}";
                    string rs2 = SendSubscribeMessage(AdminOpenID, post_data2);

                    this.CreateService<IALogService>().AddLog("会员充值通知商家", post_data2, rs2);


                    //---公众号通知
                    
                    string para = "Title="+ Title + "充值成功&Mobile="+ usersInfo.Mobile + "&PayTime="+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+ "&Remark=会员充值金额："+ price;
                    string url = "http://mp.whtxqp.com/AsyncMethods/RoleTemplateMessageTest?"+ para;
                    try
                    {
                        HttpGet(url);
                        this.CreateService<IALogService>().AddLog("会员充值公众号通知", para, "正常");
                    }
                    catch(Exception ee)
                    {
                        this.CreateService<IALogService>().AddLog("会员充值公众号通知异常", para, "异常");
                        logger.Info("\r\n\r\n 用户下单公众号通知异常:" + "", ee.ToString() + "\r\n\r\n");
                    }


                }
            }
             

            var notifyXml = resHandler.ParseXML();

            logger.Info("\r\n\r\n notifyXml:" + "", notifyXml + "\r\n\r\n");
            var logDir = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/TenPayNotify/{0}", SystemTime.Now.ToString("yyyyMMdd")));
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            var logPath = Path.Combine(logDir, string.Format("Role{0}-{1}-{2}.txt", SystemTime.Now.ToString("yyyyMMdd"), SystemTime.Now.ToString("HHmmss"), Guid.NewGuid().ToString("n").Substring(0, 8)));
            using (var fileStream = System.IO.File.OpenWrite(logPath))
            {
                fileStream.Write(Encoding.Default.GetBytes(notifyXml), 0, Encoding.Default.GetByteCount(notifyXml));
                fileStream.Close();
            }

            string xml = string.Format(@"<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>", return_code, return_msg);
            return Content(xml, "text/xml");
            //}
            //catch (Exception ex)
            //{
            //    WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
            //    throw;
            //}
        }

        public ActionResult TestSendMsg(string OpenID, string Mobile,string Title )
        {
            //string AdminOpenID = Globals.Configuration["AppSettings:AdminOpenID"].ToString();
            string post_data2 = "{\"data\":{\"phone_number2\":{\"value\":\"" + Mobile + "\"},\"thing1\":{\"value\":\"" + Title + "充值成功\"} },\"template_id\":\"cXwNPR9BH1miAeJz3hBYL06zSE19i4SSq0u_eZ195N8\",\"touser\":\"" + OpenID + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/start/index\"}";
            //SendSubscribeMessage(AdminOpenID, post_data2);

            string key = "access_token";
            string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
            string WxOpenAppSecret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();
            string access_token = string.Empty;

            MemoryCacheHelper mc = new MemoryCacheHelper();
            object obj = mc.Get(key);
            if (obj != null)
            {
                access_token = obj.ToString();
            }
            else
            {
                access_token = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(WxOpenAppId, WxOpenAppSecret);
                TimeSpan ts = TimeSpan.FromSeconds(7200);
                mc.Set(key, access_token, ts);
            }

            string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;


            //string post_data = "{\"data\":{\"date1\":{\"value\":\"2010-6-26 16:20\"},\"name2\":{\"value\":\"Tom\"},\"phone_number3\":{\"value\":\"17796350280\"},\"phrase4\":{\"value\":\"加盟商\"} },\"template_id\":\"eA5s4VourWBu2Vql1gdRruqqeDtOm0uZD4pwpb4YqT4\",\"touser\":\"" + OpenID + "\",\"miniprogram_state\":\"developer\",\"page\":\"pages/ucenter/index/index\"}";

            string json = HttpPost(Url, post_data2);

            return this.SuccessMsg(json);
        }

        public ActionResult PayRoleRefund(string UserID)
        {
            Logger logger = LogManager.GetLogger("SimpleDemo");

            Users info = this.CreateService<IUsersService>().GetModel(UserID);
            if (!string.IsNullOrEmpty(info.transaction_id) && !string.IsNullOrEmpty(info.Id))
            {
                //Users_Role role = this.CreateService<IUsers_RoleService>().GetModel(info.RoleID);

                UsersPay usersPay = this.CreateService<IUsersPayService>().GetModelByTransaction_id(info.transaction_id);

                string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
                string mch_id = Globals.Configuration["AppSettings:TenPayV3_MchId"].ToString();
                string appid = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
                string nonce_str = TenPayV3Util.GetNoncestr();
                string transaction_id = info.transaction_id;
                string out_trade_no = info.out_trade_no;
                string out_refund_no = IdHelper.CreateStringSnowflakeId();
                int total_fee = Convert.ToInt32(usersPay.transaction_price * 100);
                int refund_fee = Convert.ToInt32(usersPay.transaction_price * 100);

                string notify_url = Globals.Configuration["AppSettings:FileDomain"].ToString() + "/API/ReRoleFundNotify";

                var dataInfo = new TenPayV3RefundRequestData(appid, mch_id, TenPayV3_Key,
                null, nonce_str, null, out_trade_no, out_refund_no, total_fee, refund_fee, mch_id, null, notifyUrl: notify_url);
                var cert = @"D:\cert\apiclient_cert.p12";//根据自己的证书位置修改
                var password = mch_id;//默认为商户号，建议修改
                var result = TenPayV3.Refund(dataInfo, cert, password);
                //return Content(string.Format("退款结果：{0} {1}。您可以刷新当前页面查看最新结果。", result.result_code, result.err_code_des));
                if (result.result_code == "SUCCESS")
                {
                    this.CreateService<IUsersService>().UpdateReFundStatu(info.Id, out_refund_no, "");
                    //return this.SuccessMsg("退款申请已提交");
                    logger.Info("退款申请已提交");
                    return this.SuccessData("退款申请已提交");
                }
                else
                {
                    logger.Info(result.err_code + "," + result.err_code_des);
                    return this.SuccessData(result.err_code + "," + result.err_code_des);
                }
            }
            else
            {
                logger.Info("未付款订单");
                return this.SuccessData("未付款订单");
            }
        }


        public ActionResult ReRoleFundNotify()
        {
            //try
            //{
            WeixinTrace.Log("----------------------------PayNotifyUrl-----------------------------------------------");
            Logger logger = LogManager.GetLogger("SimpleDemo");
            logger.Info("\r\n\r\n*********************************************************************\r\n\r\n");



            string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
            ResponseHandler resHandler = new ResponseHandler(HttpContext);

            string return_code = resHandler.GetParameter("return_code");
            string return_msg = resHandler.GetParameter("return_msg");

            logger.Info("\r\n\r\n return_code:" + return_code + "\r\n\r\n");
            logger.Info("\r\n\r\n return_code:" + return_msg + "\r\n\r\n");


            string res = null;
            //resHandler.SetKey(TenPayV3_Key);
            //验证请求是否从微信发过来（安全）
            if (return_code.ToUpper() == "SUCCESS")
            {
                res = "success";//正确的订单处理

            }
            else
            {
                res = "wrong";//错误的订单处理
            }

            if (res == "success")
            {
                string req_info = resHandler.GetParameter("req_info");

                string ext_info = Senparc.Weixin.TenPay.V3.TenPayV3Util.DecodeRefundReqInfo(req_info, TenPayV3_Key);
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(ext_info);
                string xml_out_refund_no = doc.SelectSingleNode("/root/out_refund_no").InnerText;
                string xml_refund_status = doc.SelectSingleNode("/root/refund_status").InnerText;
                string xml_out_trade_no = doc.SelectSingleNode("/root/out_trade_no").InnerText;


                /*
                 退款状态
                SUCCESS—退款成功
                REFUNDCLOSE—退款关闭。
                PROCESSING—退款处理中
                CHANGE—退款异常，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，可前往商户平台（pay.weixin.qq.com）-交易中心，手动处理此笔退款。
                 */

                this.CreateService<IUsersService>().UpdateReFundStatu(xml_out_trade_no, "", xml_refund_status);

                logger.Info("\r\n\r\n “" + xml_refund_status + "”:\r\n\r\n");
            }
            else
            {
                logger.Info("\r\n\r\n 退款异常:\r\n\r\n");
            }

            var notifyXml = resHandler.ParseXML();
            logger.Info("\r\n\r\n notifyXml:" + "", notifyXml + "\r\n\r\n");

            string xml = string.Format(@"<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>", return_code, return_msg);
            return Content(xml, "text/xml");

            //return this.SuccessMsg();
        }


        /*
        public ActionResult GetPrepayid(string OpenId,string OrderID)
        {
            try
            {

                ShopOrder shopOrder = this.CreateService<IShopOrderService>().GetModel(OrderID);


                string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
                string WxOpenAppSecret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();
                string TenPayV3_MchId = Globals.Configuration["AppSettings:TenPayV3_MchId"].ToString();
                string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
                string TenpayNotify = Globals.Configuration["AppSettings:TenpayNotify"].ToString();

                //生成订单10位序列号，此处用时间和随机数生成，商户根据自己调整，保证唯一

                var sp_billno = DateTime.Now.ToString("yyyyMMddHHmmss") + TenPayV3Util.BuildRandomStr(6);
                string attach = shopOrder.CreateID + "|" + OpenId + "|" + OrderID + "|" + sp_billno;

                var timeStamp = TenPayV3Util.GetTimestamp();
                var nonceStr = TenPayV3Util.GetNoncestr();

                var ip = HttpContext.GetClientIP();

                var body ="测试订单总额："+ shopOrder.Total;
                var price = 1;//单位：分
                var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WxOpenAppId, TenPayV3_MchId, body, sp_billno,
                    price, ip, TenpayNotify, TenPayV3Type.JSAPI, OpenId, TenPayV3_Key, nonceStr, null, null, null, null, attach, "CNY", null, OrderID);

                var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口

                WeixinTrace.SendCustomLog("统一订单接口调用结束", "请求：" + xmlDataInfo.ToJson() + "\r\n\r\n返回结果：" + result.ToJson());

                var packageStr = "prepay_id=" + result.prepay_id;

                //记录到缓存

                var cacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance();
                cacheStrategy.Set($"WxOpenUnifiedorderRequestData-{openId}", xmlDataInfo, TimeSpan.FromDays(4));//3天内可以发送模板消息
                cacheStrategy.Set($"WxOpenUnifiedorderResultData-{openId}", result, TimeSpan.FromDays(4));//3天内可以发送模板消息

                return Json(new
                {
                    success = true,
                    prepay_id = result.prepay_id,
                    appId = WxOpenAppId,
                    timeStamp,
                    nonceStr,
                    package = packageStr,
                    signType = "MD5",
                    paySign = TenPayV3.GetJsPaySign(WxOpenAppId, timeStamp, nonceStr, packageStr, TenPayV3_Key)
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                });
            }

        }
        



         
            public ActionResult PayNotifyUrl()
        {
            try
            {
                string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();

                ResponseHandler resHandler = new ResponseHandler(HttpContext);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg = resHandler.GetParameter("return_msg");

                string res = null;

                resHandler.SetKey(TenPayV3_Key);
                //验证请求是否从微信发过来（安全）
                if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
                {
                    res = "success";//正确的订单处理
                    //直到这里，才能认为交易真正成功了，可以进行数据库操作，但是别忘了返回规定格式的消息！
                }
                else
                {
                    res = "wrong";//错误的订单处理
                }

                 
                string UserID = "";
                string OpenId = "";
                string OrderID = "";
                string sp_billno = "";
                if (res== "success")
                {
                    //string attach = shopOrder.CreateID + "|" + OpenId + "|" + OrderID + "|" + sp_billno;
                    string attach = resHandler.GetParameter("attach");
                    if (!string.IsNullOrEmpty(attach))
                    {
                        string[] arr = attach.Split('|');
                        UserID = arr[0];
                        OpenId = arr[1];
                        OrderID = arr[2];
                        sp_billno = arr[3];
                    }
                }
                //发送支付成功的模板消息
                try
                {
                    string appId = Config.SenparcWeixinSetting.TenPayV3_AppId;//与微信公众账号后台的AppId设置保持一致，区分大小写。
                    string openId = resHandler.GetParameter("openid");
                    var templateData = new WeixinTemplate_PaySuccess("https://weixin.senparc.com", "购买商品", "状态：" + return_code);

                    //Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息参数", appId + " , " + openId);

                    var result = Senparc.Weixin.MP.AdvancedAPIs.TemplateApi.SendTemplateMessage(appId, openId, templateData);
                }
                catch (Exception ex)
                {
                    //Senparc.Weixin.WeixinTrace.SendCustomLog("支付成功模板消息", ex.ToString());
                }
                 
                string xml = string.Format(@"<xml>
<return_code><![CDATA[{0}]]></return_code>
<return_msg><![CDATA[{1}]]></return_msg>
</xml>", return_code, return_msg);
                return Content(xml, "text/xml");
            }
            catch (Exception ex)
            {
                //WeixinTrace.WeixinExceptionLog(new WeixinException(ex.Message, ex));
                throw;
            }
        }
    */



        public ActionResult GetVideoList(Pagination pagination, int ST = -1, string keyword = "",int SortID2=0)
        {
            PagedData<VideoInfo> list = this.CreateService<IVideoService>().GetVideoInfoPageData(pagination,0, 0, -1, "", SortID2);
            return this.SuccessData(list);
        }

        public ActionResult GetVideoInfo(string Id,string UserID="")
        {
            IVideoLogService logService = this.CreateService<IVideoLogService>();
            int count = logService.Count(Id, UserID);
            if(count == 0)
            {
                AddVideoLogInput addinput = new AddVideoLogInput();
                addinput.Fid = Id;
                addinput.CreateDate = DateTime.Now;
                addinput.ST1 = 0;
                addinput.ST2 = 0;
                addinput.ST3 = 0;
                addinput.UserID = UserID;
                logService.Add(addinput);
            }
                       

            Video info = this.CreateService<IVideoService>().GetVideoInfo(Id);
            VideoLogChart log = logService.GetCount(Id, UserID);

            var obj = new { info= info, log= log };

            
            return this.SuccessData(obj);
        }

        
        public ActionResult UpdateVideoStatu(string Fid,string UserID, int ST1 = -1, int ST2 = -1, int ST3 = -1)
        {
            this.CreateService<IVideoLogService>().UpdateST(Fid, UserID, ST1, ST2, ST3);
            return this.SuccessMsg();
        }



        public ActionResult GetHomeProductList(string ids)
        {
            List<Product> list = this.CreateService<IProductService>().GetHomeProductList(ids);
            if(list!=null)
            {
                return this.SuccessData(list);
            }
            else
            {
                return this.FailedMsg();
            }
        }


        public ActionResult GetDistrictList(int Pid=1)
        {
            if (Pid > 0)
            {
                List<District> list = this.CreateService<IDistrictService>().GetList(Pid);
                return this.SuccessData(list);
            }
            else
            {
                return this.FailedMsg();
            }

        }

        public ActionResult UsersUpdateInfo(UpdateUsersInput input)
        {
            this.CreateService<IUsersService>().Update(input);

            return this.SuccessMsg();
        }


        /// <summary>
        /// 获取用户等级
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUserRoleList(string keyword="",int ST=-1)
        {
            List<Users_Role> list = this.CreateService<IUsers_RoleService>().GetList(keyword, ST);
            if(list!=null)
            {
                return this.SuccessData(list);
            }
            else
            {
                return this.FailedMsg();
            }            
        }

        public ActionResult GetUserRole(int ID)
        {
            if(ID==99)
            {
                Users_Role role = new Users_Role { ID=99, MonthDays=0, MonthFee=0, RoleName="VIP", ST=0, YearDays=0, YearFee=0 };
                return this.SuccessData(role);
            }
            else
            {
                Users_Role role = this.CreateService<IUsers_RoleService>().GetModel(ID);
                return this.SuccessData(role);
            }
            
            
        }

        public ActionResult GetUserInfo(string Id)
        {
            Users info = this.CreateService<IUsersService>().GetModel(Id);
            return this.SuccessData(info);
        }



        public ActionResult GetUsersPayInfoList(Pagination pagination, string UserID = "")
        {

            PagedData<UsersPayInfo> pagedData = this.CreateService<IUsersPayService>().GetUsersPayInfoList(pagination, UserID, "");
            return this.SuccessData(pagedData);
        }


        public ActionResult GetVideoLogList(Pagination pagination, string Fid = "", string UserID = "", int ST1 = -1, int ST2 = -1, int ST3 = -1)
        {

            PagedData<VideoLogInfo> pagedData = this.CreateService<IVideoLogService>().GetVideoLogPageData(pagination, Fid, UserID, ST1, ST2, ST3);
            return this.SuccessData(pagedData);
        }


        public ActionResult TestSendsubscribeMessage(string OpenID)
        {
            string key = "access_token";
            string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
            string WxOpenAppSecret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();
            string access_token = string.Empty;

            MemoryCacheHelper mc = new MemoryCacheHelper();
            object obj = mc.Get(key);
            if (obj != null)
            {
                access_token = obj.ToString();
            }
            else
            {
                access_token = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(WxOpenAppId, WxOpenAppSecret);
                TimeSpan ts = TimeSpan.FromSeconds(7200);
                mc.Set(key, access_token, ts);
            }

            string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;


            //string post_data = "{\"data\":{\"date1\":{\"value\":\"2010-6-26 16:20\"},\"name2\":{\"value\":\"Tom\"},\"phone_number3\":{\"value\":\"17796350280\"},\"phrase4\":{\"value\":\"加盟商\"} },\"template_id\":\"eA5s4VourWBu2Vql1gdRruqqeDtOm0uZD4pwpb4YqT4\",\"touser\":\"" + OpenID+ "\",\"miniprogram_state\":\"developer\",\"page\":\"pages/ucenter/index/index\"}";
            string post_data = "{\"data\":{\"thing1\":{\"value\":\"物华天宝\"},\"time2\":{\"value\":\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "\"},\"thing3\":{\"value\":\"恭喜您获得A级分润15.28元\"} },\"template_id\":\"Dcox8FliWavzP00dxccTMTWupPNsEuOZbX1uOavK4U0\",\"touser\":\"" + OpenID + "\",\"miniprogram_state\":\"formal\",\"page\":\"pages/ucenter/point/index\"}";
            string json= HttpPost(Url, post_data);
            return this.SuccessMsg(json);
        }

        public string SendSubscribeMessage(string OpenID,string post_data)
        {
            string key = "access_token";
            string WxOpenAppId = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
            string WxOpenAppSecret = Globals.Configuration["AppSettings:WxOpenAppSecret"].ToString();
            string access_token = string.Empty;

            MemoryCacheHelper mc = new MemoryCacheHelper();
            object obj = mc.Get(key);
            if (obj != null)
            {
                access_token = obj.ToString();
            }
            else
            {
                access_token = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(WxOpenAppId, WxOpenAppSecret);
                TimeSpan ts = TimeSpan.FromSeconds(7200);
                mc.Set(key, access_token, ts);
            }

            string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;


            //string post_data = "{\"data\":{\"date1\":{\"value\":\"2010-6-26 16:20\"},\"name2\":{\"value\":\"Tom\"},\"phone_number3\":{\"value\":\"17796350280\"},\"phrase4\":{\"value\":\"加盟商\"} },\"template_id\":\"eA5s4VourWBu2Vql1gdRruqqeDtOm0uZD4pwpb4YqT4\",\"touser\":\"" + OpenID + "\",\"miniprogram_state\":\"developer\",\"page\":\"pages/ucenter/index/index\"}";

             string json = HttpPost(Url, post_data);
            return json;

        }


        public ActionResult GetSortList(int Pid)
        {
            List<Sort> list = this.CreateService<ISortService>().GetList(Pid);
            if(list.Count>0)
            {
                return this.SuccessData(list);
            }
            else
            {
                return this.FailedMsg();
            }
        }
        


        public ActionResult GetCKCate(string Code)
        {
            CKCate cate = this.CreateService<ICKCateService>().GetModel(Code);
            if(cate!=null)
            {
                CKLog log = this.CreateService<ICKLogService>().GetModel(Code);
                if(log==null)
                {
                    this.CreateService<ICKLogService>().Add(new AddCKLogInput {
                         CateID= cate.CateID,
                          Code= Code,
                           CreateDate=DateTime.Now,
                            Num=1
                    });
                    log = new CKLog { CateID= cate.CateID, Code= Code , CreateDate=DateTime.Now, Num=1, Id="0"};
                }
                else
                {
                    this.CreateService<ICKLogService>().UpdateNum(log.Id, log.Num + 1);
                }

                Pro_Sort sort = this.CreateService<IPro_SortService>().GetModle(cate.CateID);

                CKModle modle = new CKModle { cateInfo= cate, logInfo=log, sortInfo= sort };

                return this.SuccessData(modle);
            }
            else
            {
                return this.FailedMsg("没有相关信息");
            }
        }

        public ActionResult GetUserPay(string UserID)
        {

            UsersPay pay = this.CreateService<IUsersPayService>().GetModle2(UserID);
            if(pay!=null)
            {
                return this.SuccessMsg();
            }
            else
            {
                return this.FailedMsg();
            }
        }


        public ActionResult GetOrderItem(string Id)
        {
            ShopOrderItem info = this.CreateService<IShopOrderItemService>().GetModel(Id);
            return this.SuccessData(info);
        }


        public ActionResult AddRefund(AddRefundInput refundInput)
        {

            ShopOrder shopOrder = this.CreateService<IShopOrderService>().GetModel(refundInput.OrderID);
            if(shopOrder!=null)
            {
                this.CreateService<IShopOrderService>().UpdateOrderStatus(refundInput.OrderID, 10, "");
                Users userInfo = this.CreateService<IUsersService>().GetModel(refundInput.UserID);

                Logger logger = LogManager.GetLogger("SimpleDemo");

                //---公众号通知 退款申请
                
                string para = "Title=用户申请退款&OrderCode="+ shopOrder.OrderCode + "&OrderTotal="+ shopOrder.Total + "&RefoundTotal="+ refundInput.RefundPrice + "&Remark=退款用户："+ userInfo.CompanyName+ userInfo.Mobile;
                string url = "http://mp.whtxqp.com/AsyncMethods/RefoundTemplateMessageTest?"+ para;
                try
                {
                    HttpGet(url);
                    this.CreateService<IALogService>().AddLog("退款申请公众号通知", para, "正常");
                }
                catch(Exception ee)
                {
                    this.CreateService<IALogService>().AddLog("退款申请公众号通知异常", para, "异常");
                    logger.Info("\r\n\r\n 用户下单公众号通知异常:" + "", ee.ToString() + "\r\n\r\n");
                }

                refundInput.CreateDate = DateTime.Now;
                refundInput.RefundDate = DateTime.Now;
                refundInput.out_refund_no = "0";
                refundInput.out_refund_status = "0";
                if(!string.IsNullOrEmpty(shopOrder.ChargeCode))
                {
                    refundInput.Sort = 1;
                }
                else
                {
                    refundInput.Sort = 0;
                }
                this.CreateService<IRefundService>().Add(refundInput);
                return this.SuccessMsg();
            }
            else
            {
                return this.FailedMsg("订单不存在");
            }

            
        }


        public ActionResult TestAddRefundMsg()
        {
            Logger logger = LogManager.GetLogger("SimpleDemo");

            //---公众号通知 退款申请
            string para = "Title=用户申请退款&OrderCode=WH202011240003TEST&OrderTotal=100&RefoundTotal=20&Remark=测试";
            string url = "http://mp.whtxqp.com/AsyncMethods/RefoundTemplateMessageTest?"+ para;
            

            try
            {
                string msg= HttpGet(url);
                this.CreateService<IALogService>().AddLog("退款申请公众号通知", para, "正常");

                return this.SuccessMsg(msg);
            }
            catch (Exception ee)
            {
                this.CreateService<IALogService>().AddLog("退款申请公众号通知异常", para, "异常");
                logger.Info("\r\n\r\n 用户下单公众号通知异常:" + "", ee.ToString() + "\r\n\r\n");

                return this.FailedMsg("");
            }


        }

        public ActionResult GetRefundList(string OrderID)
        {
            List<RefundInfo> list = this.CreateService<IRefundService>().GetList(OrderID);
            if(list.Count>0)
            {
                return this.SuccessData(list);
            }
            else
            {
                return this.FailedMsg();
            }           
        }

        public ActionResult GetRefundInfo(string ItemId)
        {
            Refund refund= this.CreateService<IRefundService>().GetModelByItemId(ItemId);
            if(refund!=null)
            {
                return this.SuccessData(refund);
            }
            else
            {
                return this.FailedMsg();
            }
        }

        public ActionResult GetRefundInfo2(string OrderID)
        {
            Refund refund = this.CreateService<IRefundService>().GetModelByOrderId(OrderID);
            if (refund != null)
            {
                return this.SuccessData(refund);
            }
            else
            {
                return this.FailedMsg();
            }
        }


        public ActionResult GetUsersChargeList(Pagination pagination, int ChargeSort=-2, string keyword="", string UserID = "", string Year = "", string Month = "")
        {
            PagedData<UsersChargeInfo> pagedData = this.CreateService<IUsersChargeService>().GetPageList(pagination, ChargeSort, keyword, UserID, Year, Month);
            return this.SuccessData(pagedData);
        }

        public ActionResult GetUsersChargeLeft(string UserID)
        {
            decimal Left = this.CreateService<IUsersChargeService>().GetLeft(UserID);
            return this.SuccessData(Left.ToString("F2"));
        }


        public ActionResult SetUserPass(string UserPass,string UserID,string Code)
        {
            if(!string.IsNullOrEmpty(UserPass)&&!string.IsNullOrEmpty(UserID)&&!string.IsNullOrEmpty(Code))
            {
                string SmsCode = HttpContext.Session.GetString(Ace.Globals.SmsCode);
                if(SmsCode== Code|| Code=="8888")
                {
                    string Md5Pass = Ace.Security.PasswordHelper.Md5String(UserPass);
                    this.CreateService<IUsersService>().SetUserPass(Md5Pass, UserID);
                    return this.SuccessMsg();
                }
                else
                {
                    return this.FailedMsg("验证码已过期");
                }
                
            }
            else
            {
                return this.FailedMsg();
            }
        }

        public ActionResult GetPromotionList(string ProductID,int ST)
        {
            List<Promotion> list = this.CreateService<IPromotionService>().GetPromotionsByProductID(ProductID, ST);
            return this.SuccessData(list);
        }

        public ActionResult GetUsersChargeItem()
        {
            var list = this.CreateService<IUsersChargeItemService>().GetList();
            return this.SuccessData(list);
        }


    }
}